package com.ayi.utils; /**
 * @author Ayingzz
 * @create 2021/11/29 10:48
 */

import com.ayi.bean.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(filterName = "LoginFilter"
        , urlPatterns = {"/*"}
        , initParams = {@WebInitParam(name = "loginfilter", value = "utf-8")}
        , dispatcherTypes = {DispatcherType.REQUEST})
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession(true);
        resp.setContentType("text/html;");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        String request_uri = req.getRequestURI();
        String ctxPath = req.getContextPath();
        String uri = request_uri.substring(ctxPath.length());
        System.out.println(uri);
        if (uri.contains("BackStageServlet") || uri.contains("backStage.jsp")) {
            User user = (User)session.getAttribute("user");
            if (user != null) {
                if (user.isAdmin()) {
                    chain.doFilter(request, response);
                    return;
                } else {
                    out.println("您不是管理员，没有权限进入后台，3秒后返回主页");
                    resp.setHeader("refresh", "3;url=" + ctxPath + "/IndexServlet");
                    return;
                }
            } else {
                out.println("您没有登录，请先登录！3秒后回到登录页面。");
                resp.setHeader("refresh", "1;url=" + ctxPath + "/login.jsp");
                return;
            }
        }
        System.out.println("分割线-------------------------------");
        if (uri.contains("index.jsp") || uri.contains("login.jsp") ||
                uri.contains("LoginServlet") || uri.contains("IndexServlet") ||
                uri.contains("queryServlet") || uri.contains("register.jsp") ||
                uri.contains("RegisterServlet") || uri.contains("detailsShowFromDeskServlet")) {
            chain.doFilter(request, response);
            return;
        } else {
            if (session.getAttribute("user") != null) {
                chain.doFilter(request, response);
                return;
            } else {
                out.println("您没有登录，请先登录！3秒后回到登录页面。");
                resp.setHeader("refresh", "1;url=" + ctxPath + "/login.jsp");
                return;
            }
        }
    }
}
